<template>
    <view class="volunteer-form-wrap">
        <view class="title">爱心捐物信息</view>

        <view class="form-box">
            <!-- 必填项 -->
            <view class="form-item">
                <view class="label required">姓名</view>
                <input class="input" v-model="formData.name" placeholder="请输入" @blur="validateField('name')" />
            </view>

            <view class="form-item">
                <view class="label required">联系方式</view>
                <input class="input" v-model="formData.phone" placeholder="请输入" type="number"
                    @blur="validateField('phone')" />
            </view>

            <view class="form-item">
                <view class="label">联络地址</view>
                <input class="input" v-model="formData.addr" placeholder="请输入" />
            </view>

            <view class="form-item">
                <view class="label">物品名称</view>
                <input class="input" v-model="formData.itemName" placeholder="请输入" />
            </view>

            <view class="form-item">
                <view class="label">单价（元）</view>
                <input class="input" v-model="formData.price" placeholder="请输入" type="digit" @input="calculateTotal" />
            </view>

            <view class="form-item">
                <view class="label">规格</view>
                <input class="input" v-model="formData.itemSpec" placeholder="请输入" />
            </view>

            <view class="form-item">
                <view class="label">数量</view>
                <input class="input" v-model="formData.nums" placeholder="请输入" type="number" @input="calculateTotal" />
            </view>

            <view class="form-item">
                <view class="label">总金额（元）</view>
                <input class="input" v-model="formData.amount" placeholder="请输入" disabled />
            </view>

            <view class="form-item">
                <view class="label">捐赠意向</view>
                <input class="input" v-model="formData.intention" placeholder="请输入" />
            </view>

            <view class="form-item">
                <view class="label">备注</view>
                <input class="input" v-model="formData.remark" placeholder="请输入" />
            </view>
        </view>

        <view class="footer-btn">
            <view class="primary-btn" @click="submitForm">提交申请</view>
        </view>
    </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import {
    validateRequired,
    validatePhoneWithError
} from '@/utils/validation.js'
import { donateMaterial } from '@/utils/api.js'

// 表单数据
const formData = reactive({
    name: '',
    phone: '',
    addr: '',
    itemName: '',
    price: '',
    itemSpec: '',
    nums: '',
    amount: '',
    intention: '',
    remark: ''
})

// 错误信息
const errors = reactive({
    name: '',
    phone: ''
})

// 计算总金额
const calculateTotal = () => {
    const price = parseFloat(formData.price) || 0
    const quantity = parseInt(formData.nums) || 0
    const total = price * quantity
    formData.amount = total.toFixed(2)
}

// 字段验证
const validateField = (field) => {
    errors[field] = ''

    switch (field) {
        case 'name':
            errors.name = validateRequired(formData.name, '姓名')
            break
        case 'phone':
            errors.phone = validatePhoneWithError(formData.phone, '联系方式')
            break
    }
}

// 表单提交
const submitForm = async () => {
    // 验证所有必填字段
    const requiredFields = ['name', 'phone']
    let isValid = true

    requiredFields.forEach(field => {
        validateField(field)
        if (errors[field]) {
            isValid = false
        }
    })

    if (!isValid) {
        uni.showToast({
            title: '请完善必填信息',
            icon: 'none'
        })
        return
    }

    // 显示加载提示
    uni.showLoading({
        title: '提交中...'
    })

    try {
        // 准备提交数据，按照API接口参数要求
        const submitData = {
            name: formData.name,
            phone: formData.phone,
            addr: formData.addr || '',
            itemName: formData.itemName || '',
            price: formData.price ? parseFloat(formData.price) : undefined,
            itemSpec: formData.itemSpec || '',
            nums: formData.nums || '',
            amount: formData.amount || '',
            intention: formData.intention || '',
            remark: formData.remark || ''
        }

        // 提交表单
        const result = await donateMaterial(submitData)

        uni.hideLoading()

        if (result.code === 0) {
            uni.showToast({
                title: '申请提交成功',
                icon: 'success'
            })

            // 延迟跳转回首页
            setTimeout(() => {
                uni.navigateTo({
                    url: '/pages/moneyAndMaterials/index'
                })
            }, 1500)
        } else {
            uni.showToast({
                title: result.msg || '提交失败',
                icon: 'none'
            })
        }
    } catch (error) {
        uni.hideLoading()
        console.error('提交失败:', error)
        uni.showToast({
            title: '网络错误，请重试',
            icon: 'none'
        })
    }
}

// 页面加载时获取状态
onMounted(() => {
    // 页面初始化
})
</script>

<style lang="scss" scoped>
.volunteer-form-wrap {
    padding: 24rpx;
    background: #f5f5f5;
    padding-bottom: 200rpx;

    .title {
        font-size: 32rpx;
        font-weight: 600;
        line-height: 52rpx;
        color: #000;
        padding: 20rpx 10rpx;
    }

    .form-box {
        background: #FFFFFF;
        border-radius: 16rpx;
        padding: 0 24rpx;
        border: 2rpx solid #E7E8EB;

        .form-item {
            min-height: 84rpx;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 2rpx solid #F6F6F6;
            padding: 16rpx 0;

            &:last-child {
                border-bottom: none;
            }

            .label {
                font-size: 28rpx;
                color: rgba(0, 0, 0, 0.60);
                font-weight: 500;
                min-width: 160rpx;

                &.required::after {
                    content: '*';
                    color: #ff4757;
                    margin-left: 4rpx;
                }
            }

            .input {
                flex: 1;
                font-size: 28rpx;
                height: 84rpx;
                padding: 0 16rpx;
                background: #ffffff;
                text-align: right;

                &::placeholder {
                    color: rgba(0, 0, 0, 0.3);
                }

                &:disabled {
                    background: #f5f5f5;
                    color: #999;
                }
            }

            .textarea {
                flex: 1;
                font-size: 28rpx;
                padding: 16rpx;
                background: #ffffff;
                border: 1rpx solid #e0e0e0;
                border-radius: 8rpx;
                resize: none;

                &::placeholder {
                    color: rgba(0, 0, 0, 0.3);
                }
            }
        }
    }
}

.footer-btn {
    position: fixed;
    bottom: 0;
    left: 0;
    width: calc(100% - 48rpx);
    height: 100rpx;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 24rpx 24rpx 28rpx 24rpx;
    z-index: 100;

}
</style>